package com.zy.rpc.common.codec;

import com.zy.rpc.common.Serializer.Serializer;
import com.zy.rpc.common.Serializer.SerializerFactory;
import com.zy.rpc.common.ask.RpcRequest;
import com.zy.rpc.common.ask.RpcResponse;
import com.zy.rpc.common.constants.MsgType;
import com.zy.rpc.common.constants.ProtocolCons;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apache.log4j.Logger;
import java.nio.charset.StandardCharsets;
import java.util.UUID;


/**
 * @author zy
 * @date 2023/5/14 19:04
 */


public class RpcEncoder extends MessageToByteEncoder<Object> {
    private static final Logger log=Logger.getLogger(RpcEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (msg instanceof RpcRequest) {
            RpcRequest rpcRequest = (RpcRequest) msg;
            // 编码 RpcRequest 对象
            out.writeBytes(ProtocolCons.magic);//字节魔数
            out.writeByte(ProtocolCons.version);//版本
            out.writeByte(ProtocolCons.version);//序列化方式
            out.writeByte(MsgType.REQUEST.getType());//消息类型
            //消息id
            out.writeCharSequence(UUID.randomUUID().toString().replaceAll("-", ""), StandardCharsets.UTF_8);
            Serializer defaultSerializer = SerializerFactory.getDefaultSerializer();
            byte[] bytes = SerializerFactory.getDefaultSerializer().serialize(rpcRequest);
            int length = bytes.length;
            out.writeInt(length);
            out.writeBytes(bytes);
        }
        else if (msg instanceof RpcResponse) {

            // 编码 RpcResponse 对象
            RpcResponse response = (RpcResponse) msg;
            out.writeBytes(ProtocolCons.magic);//字节魔数
            out.writeByte(ProtocolCons.version);//版本
            out.writeByte(ProtocolCons.version);//序列化方式
            out.writeByte(MsgType.RESPONSE.getType());//消息类型
            //消息id
            out.writeCharSequence(UUID.randomUUID().toString().replaceAll("-", ""), StandardCharsets.UTF_8);
            byte[] bytes = SerializerFactory.getDefaultSerializer().serialize(response);
            int length = bytes.length;
            out.writeInt(length);
            out.writeBytes(bytes);
        } else {
            throw new IllegalArgumentException("Unsupported message type: " + msg.getClass().getName());
        }
    }
}
